package com.jinzhi.jzweb.utils;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

public class MyTask implements  Comparable<MyTask>{


    private Runnable runnable;//描述要执行的任务
    private long time;//什么时间执行,用时间戳来表示

    public MyTask(Runnable task,long delay){
        this.runnable = task;
        this.time = System.currentTimeMillis() + delay;
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTask o) {
        return (int) (this.getTime()-o.getTime());
    }
}
//定时器
class MyTimer {
    private BlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();
    Object locker = new Object();
    public MyTimer(){
        Thread t = new Thread(() -> {
            while (true){
                synchronized (locker) {
                    try {
                        MyTask task = queue.take();//获取队首元素
                        long curTime = System.currentTimeMillis();//获取当前时间
                        //比较当前时间和队首元素的执行时间
                        if(curTime >= task.getTime()){
                            //时间到，执行任务
                            task.getRunnable().run();
                        }else {
                            //时间没到，把元素再放回到队列中
                            queue.put(task);
                            locker.wait(task.getTime() - curTime);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        t.start();
    }
    public void schedule(Runnable task,long delay) throws InterruptedException {
        MyTask myTask = new MyTask(task, delay);
        //把任务放入队列中
        queue.put(myTask);
        synchronized (locker){
            locker.notify();
        }
    }



}
